package com.xehy.service.impl;



import com.xehy.entity.Teacher;
import com.xehy.security.GrantedAuthorityImpl;
import com.xehy.security.JwtUserDetails;
import com.xehy.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author RSW
 * @create 2020/12/25 0025 14:08
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private TeacherService teacherService;

    @Override
    public JwtUserDetails loadUserByUsername(String userName) {
            Teacher teacher = teacherService.findByName(userName);
            if (Objects.isNull(teacher)) {
                throw new UsernameNotFoundException("该用户不存在");
            }
            // 查找用户权限列表，根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比，决定是否可以调用接口
            Set<String> permissions = teacherService.findPermissions(teacher);
            List<GrantedAuthority> grantedAuthorities = permissions.stream().map(GrantedAuthorityImpl::new).collect(Collectors.toList());
            return new JwtUserDetails(teacher.getTeacherName(), teacher.getTeacherPassword(), teacher.getSalt(), teacher.getTeacherId(),grantedAuthorities);
    }
}
